<?php
namespace app\home\controller;
use app\common\validate\Post as postValidate;
use think\exception\ValidateException;
use think\facade\Db;
use app\common\model\Post as P;
use think\facade\Request;
use think\facade\View;

class Post extends Base
{

    //文章详情页
    function detail()
    {
        $id = input('id');
        Db::name('post')->where('id',$id)->inc('read_count')->update();
        $detail = P::withJoin(['userInfo'	=>	['username','uid'],'cate' =>['cate_name']])->where('id',$id)->where("tn_post.status",0)->order("id desc")->find();
        if(!$detail){
            abort(404, '找不到该页面！');
        }


        return view("/article-detail",[
            "article" => $detail,
        ]);

    }

    public function postCate()
    {
        $cateId = input("id");

        $where["tn_post.status"] = 0;
        if ($cateId > 0){
            $where["tn_post.cate_id"] = $cateId;
        }

        $list = P::withJoin(['userInfo'	=>	['username','uid'],'cate' =>['cate_name']])->where($where)->order("id desc")->paginate(10);
        $cateName = Db::name("category")->where("cate_id",$cateId)->value("cate_name");
        $cateList = Db::name("category")->select()->toArray();

        foreach ($cateList as $key =>$item){
            $cateList[$key]["postCount"] = Db::name("post")->where("cate_id",$item["cate_id"])->count();
        }

        $allPostCount = Db::name("post")->count();
        View::assign("list",$list);
        View::assign("cateName",$cateName);
        View::assign("cateList",$cateList);
        View::assign("allPostCount",$allPostCount);
        return view("/cate-post");
    }

    public function newList()
    {
        $list = P::withJoin(['userInfo'	=>	['username','uid'],'cate' =>['cate_name']])->where("tn_post.status",0)->order("id desc")->paginate(10);
        return json($list);
    }

    public function postAdd()
    {
        $id = input("id");
        if (request()->isAjax()){
            $data = input("post.");

            $order=array("\r\n","\n","\r");
            $replace='<br/>';
            $data["content"]=str_replace($order,$replace,$data["content"]);

            try {
                validate(postValidate::class)->check($data);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return json(["code" => 0,"msg" =>$e->getError()]);
            }

            if (empty($id)){
                $data["status"] = 1;
                preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',input("content","","trim"), $ereg);//正则表达式把图片的SRC获取出来了
                if(empty($ereg)) {
                    $cover_image = "";
                }else{
                    $cover_image = $ereg[1];//图片SRC
                }
                $data["cover_image"] = $cover_image;
                $data["uid"] = session("UID");
                $create = P::create($data);
                if ($create){
                    $wxSend = new Wechat();

                    $cataName = Db::name("category")->where("cate_id",$data["cate_id"])->value("cate_name");
                    $openid = "o_MmO08-KweMWIQRapBSEvhwzeYQ"; //公众号有所者openid
                    $templateId = "5n2KP04d9cfbDglR6xCY6Nrk45w01Frinj4Xo_9DD_g";
                    $first =  ["value" =>"新文章待审核","color" => "#173177" ];
                    $keyword1 =  ["value" =>"《".$data["title"] ."》","color" => "#173177" ];
                    $keyword2 =  ["value" =>"待审核","color" => "#173177" ];
                    $remark =  ["value" =>"","color" => "#173177" ];

                    $wxSend->wxSendMember($openid,$templateId, $first,$keyword1,$keyword2,[],$remark);

                    return json(["code" => 1,"msg" =>"投稿成功，等待管理员审核"]);
                }
                return json(["code" => 0,"msg" =>"投稿失败"]);
            }else if ($id > 0){
                $update = P::update($data);
                if ($update){
                    return json(["code" => 1,"msg" =>"修改成功"]);
                }
                return json(["code" => 0,"msg" =>"修改失败"]);
            }
        }else{
            $postDetail = P::find($id);
            $category = Db::name("category")->select();
            View::assign("category",$category);
            View::assign("postDetail",$postDetail);
            return View::fetch("/user/post-add");
        }
    }

    public function delPost()
    {
        $id = input("post_id");
        $del = P::destroy($id);
        if ($del){
            return json(["code" => 1,"msg" =>"删除成功"]);
        }
        return json(["code" => 0,"msg" =>"删除失败"]);
    }

    public function cancelCollection()
    {
        $id = input("post_id");

        $where["uid"] = session("UID");
        $where["post_id"] = $id;
        $del = Db::name("post_collection")->where($where)->delete();
        if ($del){
            return json(["code" => 1,"msg" =>"已取消收藏"]);
        }
        return json(["code" => 0,"msg" =>"取消收藏失败"]);
    }
}